//
//  StatusPictureView.swift
//  weibo
//
//  Created by 张宏芝 on 15/9/7.
//  Copyright © 2015年 kama. All rights reserved.
//

import UIKit
import SDWebImage

//    可重用标识符
private let HMStatusPictureViewCellID = "HMStatusPictureViewCellID"

// 选中照片通知
let HZStatusPictureViewSelectedPhotoNotification = "HZStatusPictureViewSelectedPhotoNotification"
/// 选中索引 Key
let HZStatusPictureViewSelectedPhotoIndexPathKey = "HZStatusPictureViewSelectedPhotoIndexPathKey"
/// 选中的图片 URL Key
let HZStatusPictureViewSelectedPhotoURLsKey = "HZStatusPictureViewSelectedPhotoURLsKey"

class StatusPictureView: UICollectionView {

/// 微博数据视图模型,如果是新的cell才会被设置模型
    var statusViewModel:StatusViewModel?{
        didSet{
            sizeToFit()
/// 刷新数据
            reloadData()
        }
    }
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calViewSize()
    }
    private func calViewSize()->CGSize{
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
//        设置默认大小
        layout.itemSize = CGSize(width: HMStatusPictureItemWidth, height: HMStatusPictureItemWidth)
        let count = statusViewModel?.thumbnailURLs?.count ?? 0
        
//        1> 没有图
        if count == 0 {
            return CGSizeZero
        }
//        2> 1张图
        if count == 1 {
            var size = CGSize(width: 150, height: 150)
//            判断图片是否正确进行缓存,key是URL的完整字符串
            let key = statusViewModel?.thumbnailURLs![0].absoluteString
//            如果有缓存,记录当前图片的大小
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key){
                size = image.size
            }
//            单独处理过宽或是窄的图片
            size.width = size.width < 40 ? 40 :size.width
            size.width = size.width > 300 ?300 :size.width
            
            layout.itemSize = size
            return size
        }
//        3> 4张图
        if count == 4 {
            let w = 2 * HMStatusPictureItemWidth + HMStatusPictureItemMargin
            return CGSize(width: w, height: w)
        }
//        4>其他
        let row = CGFloat((count - 1) / Int(HMStatusPictureMaxCount) + 1)
        let h = row * HMStatusPictureItemWidth + (row - 1) * HMStatusCellMargin
        let w = HMStatusPictureMaxWidth
        return CGSize(width: w, height: h)
    }
//    构造函数的调用是底层自动转发的  init()->initWithFrame->initWithFrame:layout:
//    默认的layout 没有被初始化
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
       
        backgroundColor = UIColor.lightGrayColor()
//        设置布局的间距
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.minimumInteritemSpacing = HMStatusPictureItemMargin
        layout.minimumLineSpacing = HMStatusPictureItemMargin
        
//        指定数据源----自己充当自己的数据源
//        指定数据源与代理
//        1.在自定义View中,代码逻辑比较简单,可以考虑自己充当自己的数据源
//        2.dataSource与delegate本身就是弱引用,自己充当自己的代理不会产生循环引用的问题
        dataSource = self
        delegate = self
//        注册可重用cell
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier: HMStatusPictureViewCellID)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension StatusPictureView:UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        printLog(indexPath)
        printLog(statusViewModel?.bmiddleURLs)

//      测试起始位置与目标位置的代码
//        let v = UIView(frame:fullScreenRect(indexPath))
//        v.backgroundColor = UIColor(white: 0.0, alpha: 0.5)
//        UIApplication.sharedApplication().keyWindow?.addSubview(v)
        
//        发送通知
        // object:发送的对象,可以传递一个数值,也可以是"自己",通过obj.属性
        // userInfo:可选字典,可以传递多个数值,object必须有数值
        NSNotificationCenter.defaultCenter().postNotificationName(HZStatusPictureViewSelectedPhotoNotification, object: self,
            userInfo: [HZStatusPictureViewSelectedPhotoIndexPathKey:indexPath,
                HZStatusPictureViewSelectedPhotoURLsKey:statusViewModel!.bmiddleURLs!])
    }
    
//    返回指定的indexPath对应cell在屏幕上的坐标位置
    func screenRect(indexPath:NSIndexPath)->CGRect{
        let cell = cellForItemAtIndexPath(indexPath)
        
//        转换坐标convert,每一个视图的frame都是相对父视图来定义的
//        同一个位置,需要知道在其他视图中得相对应的位置,可以使用convert函数
//        UIView本身遵循了UICoordinateSpace协议,该协议提供了坐标转换的方法
        return convertRect(cell!.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
    }
    
//    图片完全放大后的背景图片
    func fullScreenRect(indexPath:NSIndexPath)->CGRect{
//        根据缩略图片,计算目标的尺寸
//        1.拿到缩略图
        let key = statusViewModel!.thumbnailURLs![indexPath.item].absoluteString
        let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
//        2.根据图像计算宽高比例
        let scale = image.size.height / image.size.width
        let w = UIScreen.mainScreen().bounds.width
        let h = w * scale
//        3.判断高度
        var y = (UIScreen.mainScreen().bounds.height - h) * 0.5
        if y < 0{  // 如果图片的高度大于屏幕的高度,让图片置顶
            y = 0
        }
        return CGRect(x: 0, y: y, width: w, height: h)
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return statusViewModel?.thumbnailURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HMStatusPictureViewCellID, forIndexPath: indexPath) as! StatusPictureViewCell
        cell.imageURL = statusViewModel!.thumbnailURLs![indexPath.item]
        return cell
    }
}

// 配图视图的Cell
private class StatusPictureViewCell: UICollectionViewCell {

//    配图视图的URL
    var imageURL: NSURL? {
        didSet{
            iconView.sd_setImageWithURL(imageURL)
//            在设置图像URL的时候,根据图片的扩张名字判断是不是GIF图片
            // absoluteString:图像的全部路径
            // pathExtension:图像的扩展名
            //  lowercaseString:小写字母
            gifIconView.hidden = (imageURL!.absoluteString as NSString).pathExtension.lowercaseString != "gif"
        }
    }
    
//  MARK:构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(iconView)
        iconView.addSubview(gifIconView)
        
        iconView.ff_Fill(self)
        gifIconView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: iconView, size: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//    MARK:懒加载
    private lazy var iconView:UIImageView = {
        let iv = UIImageView()
//        设置填充模式
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true
        return iv
        
    }()
//    gif图片
    private lazy var gifIconView:UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
}



















































